package info.leetcode.answer.Link.moveOrInsert;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaolong
 * @version 1.0
 * @description: 设计链表
 * @date 2024/3/11 10:26
 */
public class MyLinkedList {

    Integer data;
    Integer size = 0;
    MyLinkedList nextNode;


    public MyLinkedList() {
        super();
    }

    public int get(int index) {
        if (index >= size) {
            return -1;
        }
        MyLinkedList A = nextNode;
        for (int i = 0; i < index; i++) {
            A = A.nextNode;
        }
        return A.data;
    }

    public void addAtHead(int val) {
        MyLinkedList A = nextNode;
        MyLinkedList B = new MyLinkedList();
        B.data = val;
        if (A != null) {
            B.nextNode = A;
        }
        nextNode = B;
        size++;

    }

    public void addAtTail(int val) {
        MyLinkedList A = nextNode;
        MyLinkedList B = null;
        MyLinkedList C = new MyLinkedList();
        C.data = val;
        while (A != null) {
            B = A;
            A = A.nextNode;
        }
        if (B == null) {
            nextNode = C;
        } else {
            B.nextNode = C;
        }
        size++;

    }

    public void addAtIndex(int index, int val) {
        if (index == size) {
            addAtTail(val);
        } else if (index > size) {
            return;
        } else if (index == 0) {
            addAtHead(val);
        } else {
            MyLinkedList A = nextNode;
            for (int i = 1; i < index; i++) {
                A = A.nextNode;
            }
            MyLinkedList myLinkedList = new MyLinkedList();
            myLinkedList.data = val;
            myLinkedList.nextNode = A.nextNode;
            A.nextNode = myLinkedList;
            size++;
        }

    }

    public void deleteAtIndex(int index) {
        if (index >= size) {
            return;
        }
        if (index == 0) {
            nextNode = nextNode.nextNode;
            size--;
            return ;
        }
        MyLinkedList A = nextNode.nextNode;
        MyLinkedList B = nextNode;
        for (int i = 1; i < index; i++) {
            B = A;
            A = A.nextNode;
        }
        B.nextNode = A.nextNode;
        size--;
    }

    public static void main(String[] args) {
        MyLinkedList myLinkedList = new MyLinkedList();
        myLinkedList.addAtHead(1);
        myLinkedList.addAtTail(3);
        myLinkedList.addAtIndex(1,2);
        myLinkedList.get(1);
        myLinkedList.deleteAtIndex(1);
        myLinkedList.get(1);
        myLinkedList.get(3);
        myLinkedList.deleteAtIndex(3);
        myLinkedList.deleteAtIndex(0);
        myLinkedList.get(0);
        myLinkedList.deleteAtIndex(0);
        myLinkedList.get(0);
    }
}

